<template>
  <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" label-position="left" label-width="0px">
    <el-form-item prop="username">
      <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
        <template #prepend><Icon class="leftIcon" icon="Avatar"></Icon></template>
      </el-input>
    </el-form-item>
    <el-form-item prop="password">
      <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码">
        <template #prepend><Icon class="leftIcon" icon="Lock"></Icon></template>
      </el-input>
    </el-form-item>
    <el-checkbox v-model="remberMe" label="记住密码" style="margin-bottom: 18px" size="large" />
    <el-form-item style="width: 100%">
      <el-button v-loading="loading" size="large" type="primary" style="width: 100%" @click.prevent="handleLogin">
        <span v-if="!loading">登 录</span>
      </el-button>
    </el-form-item>
  </el-form>
</template>

<script setup lang="ts">
import { useAllStore, routeType } from "@/store/modules/base";
const store = useAllStore();
const loading = ref(false);
const loginFormRef = ref();
const router = useRouter();
const remberMe = ref(true);
let loginForm = reactive({ username: "", password: "" });
const loginRules = {
  username: [{ required: true, trigger: "blur", message: "用户名不能为空" }],
  password: [{ required: true, trigger: "blur", message: "密码不能为空" }]
};
interface infoType {
  token: string;
  user: { username: string; avatar: string };
}
const getMenuByAccess = async () => {
  if (!router.options.routes[0].children) return;
  let arr: routeType[] = [];
  router.options.routes[0].children.map((ite) => {
    if (ite.meta?.menu) arr.push(ite as routeType);
  });
  store.menu = arr;
  router.push(arr[0] ? arr[0].path : "/");
};
function handleLogin() {
  loginFormRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      return false;
    }
    let res = await hfoRequest.post<infoType>({ url: "/login", data: loginForm });
    store.user = res.data.user;
    if (res?.flag) {
      store.token = `${res.data.token}`;
      remberMe.value
        ? (store.account = {
            username: loginForm.username,
            password: loginForm.password
          })
        : (store.account = {});
      getMenuByAccess();
    }
  });
}

if (store.account) {
  loginForm = Object.assign(loginForm, store.account);
  remberMe.value = true;
}
</script>

<style scoped lang="scss">
.el-form-item {
  height: 38px;
}
.el-input {
  height: 38px;
  input {
    height: 38px;
  }
}
.input-icon {
  height: 39px;
  width: 14px;
  margin-left: 2px;
}
</style>
